package org.jeecg.modules.wechat.controller;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.jeecg.modules.demo.authorizationinfo.entity.AppStore;
import org.jeecg.modules.demo.authorizationinfo.entity.AuthorizationInfo;
import org.jeecg.modules.demo.authorizationinfo.service.IAuthorizationInfoService;
import org.jeecg.modules.demo.storeinfo.entity.StoreInfo;
import org.jeecg.modules.demo.storeinfo.service.IStoreInfoService;
import org.jeecg.modules.wechat.config.WechatThirdConfig;
import org.jeecg.modules.wechat.error.WechatErrorException;
import org.jeecg.modules.wechat.result.auth.ApiQueryAuthInfo;
import org.jeecg.modules.wechat.result.xcx.*;
import org.jeecg.modules.wechat.service.WechatThirdAuthService;
import org.jeecg.modules.wechat.service.WechatThirdMiniProgramService;

import org.jeecg.modules.wechat.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author
 * @date 2018/11/7
 * 微信授权流程
 */
@RestController
@RequestMapping("/wechat/third/auth")
public class WechatThirdAuthController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private WechatThirdConfig wechatThirdConfig;
    @Autowired
    private WechatThirdAuthService wechatThirdAuthService;
    @Autowired
    private WechatThirdMiniProgramService wechatThirdMiniProgramService;
    @Autowired
    private IAuthorizationInfoService authorizationInfoService;
    @Autowired
    private IStoreInfoService storeInfoService;

    /**
     * 一键授权按钮
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping("/goto_auth_url_show")
    public String gotoPreAuthUrlShow(HttpServletResponse response) throws Exception{
        return "<a href='goto_auth_url'>一键授权</a>";
    }


    /**
     * 授权注册页面扫码授权   显示二维码
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goto_auth_url", method = RequestMethod.GET)
    public void gotoPreAuthUrl(HttpServletRequest request, HttpServletResponse response) throws WechatErrorException {
        String host = request.getHeader("host");
        String url = "https://"+host+"/fubaihui/wechat/third/auth/jump";
        try {
            url = wechatThirdAuthService.getPreAuthUrl(url, null, null);
            response.sendRedirect(url);
        } catch (WechatErrorException | IOException e) {
            logger.error("gotoPreAuthUrl", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 授权成功回调链接
     * @param authorizationCode
     * 这边可以直接 重定向自己前台的页面   也可判断权限是否全部勾选完成  授权完成后把授权小程序的信息保存好
     * @return
     */
    @GetMapping("/jump")
    public ApiQueryAuthInfo jump(@RequestParam("auth_code") String authorizationCode,
                                 @RequestParam(value = "expires_in", required = false) Integer expiresIn, HttpServletResponse response){
        try {
            ApiQueryAuthInfo apiQueryAuthInfo = wechatThirdAuthService.getApiQueryAuthInfo(authorizationCode);
            AuthorizationInfo authorizationInfo = authorizationInfoService.getByAppid(apiQueryAuthInfo.getAuthorizationInfo().getAuthorizerAppid());
            if(authorizationInfo == null)
            {
                logger.info("sava authorizationInfo start...");
                authorizationInfo = new AuthorizationInfo();
                authorizationInfo.setAuthorizerAppid(apiQueryAuthInfo.getAuthorizationInfo().getAuthorizerAppid());
                authorizationInfo.setAuthorizerAccessToken(apiQueryAuthInfo.getAuthorizationInfo().getAuthorizerAccessToken());
                authorizationInfo.setExpiresIn(apiQueryAuthInfo.getAuthorizationInfo().getExpiresIn());
                authorizationInfo.setAuthorizerRefreshToken(apiQueryAuthInfo.getAuthorizationInfo().getAuthorizerRefreshToken());
                authorizationInfo.setCreateBy("sys");
                authorizationInfo.setCreateTime(new Date());
                authorizationInfo.setUpdateBy("sys");
                authorizationInfo.setUpdateTime(new Date());
                authorizationInfoService.save(authorizationInfo);
                logger.info("sava authorizationInfo end");
                logger.info("sava authorizationInfo end:"+authorizationInfo.getAuthorizerAppid());
            }
            else
            {
                logger.info("update authorizationInfo start...");
                authorizationInfo.setAuthorizerAppid(apiQueryAuthInfo.getAuthorizationInfo().getAuthorizerAppid());
                authorizationInfo.setAuthorizerAccessToken(apiQueryAuthInfo.getAuthorizationInfo().getAuthorizerAccessToken());
                authorizationInfo.setExpiresIn(apiQueryAuthInfo.getAuthorizationInfo().getExpiresIn());
                authorizationInfo.setAuthorizerRefreshToken(apiQueryAuthInfo.getAuthorizationInfo().getAuthorizerRefreshToken());
                authorizationInfo.setUpdateBy("sys");
                authorizationInfo.setUpdateTime(new Date());
                authorizationInfoService.updateById(authorizationInfo);
                logger.info("update authorizationInfo end");
                logger.info("update authorizationInfo end"+authorizationInfo.getAuthorizerAppid());
            }
            logger.info("getQueryAuth", apiQueryAuthInfo);
            return apiQueryAuthInfo;
        } catch (WechatErrorException e) {
            logger.error("gotoPreAuthUrl", e);
            throw new RuntimeException(e);
        }
    }


    /**
     * 授权完成后可提交审核（批量提交）
     */
    @PostMapping("/commit")
    public Boolean commit() throws Exception {

        List<AppStore> listAppStore = authorizationInfoService.listAppStore();
        if(listAppStore != null)
        {
            if(listAppStore.size() > 0){
                for(int index=0;index<listAppStore.size();index++){
                    /**
                     * 授权小程序的id
                     */
                    String authorizerAppId = listAppStore.get(index).getAuthorizerAppid();
                    /**
                     * 1、使用token调用微信接口modify_domain更换小程序的服务器域名，以便代替微信对小程序或公众号进行运营管理。
                     */
                    ApiModifyDomainInfo apiModifyDomainInfo = wechatThirdMiniProgramService.modifyDomain(authorizerAppId, "set", wechatThirdConfig.getRequestDomain(), wechatThirdConfig.getWsrequestDomain(), wechatThirdConfig.getUploadDomain(), wechatThirdConfig.getDownloadDomain());


                    /**
                     * 2、在微信第三方平台设置页面里上传一个开发小程序的代码的，并添加为模板，取得模板ID
                     */
                    List<TemplateListResult> templateListResultList = wechatThirdMiniProgramService.getTemplateList();
                    /**
                     * 取最新的一个模板
                     */
                    Collections.sort(templateListResultList, Comparator.comparing(TemplateListResult::getCreateTime).reversed());
                    TemplateListResult template = templateListResultList.get(0);


                    /**
                     * 3、在第三方平台开发程序中调用微信接口/wxa/commit传入参数：ext_json
                     */
                    Map<String, Object> map = new HashMap<>();
                    map.put("storeId", listAppStore.get(index).getStoreId());//自定义参数
                    ApiCodeCommitExtParameter apiCodeCommitExtParameter = ApiCodeCommitExtParameter
                            .builder().extAppid(authorizerAppId)
                            .extEnable(true)
                            .directCommit(false)
                            .ext(map).build();
                            //.extPages(pageMap)
                            //.pages(Lists.newArrayList("index","search/index"))
                            //.networkTimeout(ApiCodeCommitExtParameter.NetworkTimeout.builder().build())
                            //.tabBar(ApiCodeCommitExtParameter.TabBar.builder().build())
//                            .window(ApiCodeCommitExtParameter.Window
//                                    .builder()
//                                    .navigationBarTitleText(listAppStore.get(index).getStoreName())
//                                    .build()).build();

                    /**
                     * 4、在第三方平台开发程序中调用微信接口/wxa/commit传入参数：ext_json
                     */
                    ApiSetWebviewDomainInfo apiSetWebviewDomainInfo = wechatThirdMiniProgramService.codeCommit(authorizerAppId, template.getTemplateId(), template.getUserVersion(), template.getUserDesc(), apiCodeCommitExtParameter);


                    /**
                     * 5 获取授权小程序帐号的可选类目
                     */
                    CategoryListResult categoryList = wechatThirdMiniProgramService.getCategoryList(authorizerAppId);

                    /**
                     * 6 获取小程序的第三方提交代码的页面配置（仅供第三方开发者代小程序调用）
                     */
                    PageListResult pageList = wechatThirdMiniProgramService.getPageList(authorizerAppId);


                    /**
                     * 7 将第三方提交的代码包提交审核
                     */
                    List<SubmitAuditParameter.Item> items = Lists.newArrayList();
                    for (int i = 0; i < categoryList.getCategoryList().size(); i++) {
                        if(i<5){
                            CategoryListResult.CategoryList category = categoryList.getCategoryList().get(i);
                            SubmitAuditParameter.Item item = SubmitAuditParameter.Item.builder()
                                    .address(pageList.getPageList().get(0))
                                    .tag(getMiniPragramTag(category.getFirstClass(), category.getSecondClass(), category.getThirdClass()))
                                    .first_class(category.getFirstClass())
                                    .first_id(category.getFirstId())
                                    .second_class(category.getSecondClass())
                                    .third_class(category.getThirdClass())
                                    .third_id(category.getThirdId())
                                    .second_id(category.getSecondId())
                                    .title(listAppStore.get(index).getStoreName())
                                    .build();
                            items.add(item);
                        }

                    }
                    SubmitAuditParameter submitAuditParameter = SubmitAuditParameter
                            .builder()
                            .order_path("user/order/index")
                            .item_list(items).build();
                    SubmitAuditResult submitAuditResult = wechatThirdMiniProgramService.submitAudit(authorizerAppId, submitAuditParameter);
                }
            }
        }
        return true;
    }

    /**
     * 授权完成后可提交审核(单独提交)
     */
    @PostMapping("/commitOne")
    public Boolean commitOne(@RequestBody Map<String, Object> params) throws Exception {
        /**
         * 授权小程序的id
         */
        String authorizerAppId = params.get("xcxAppid") == null ? null : String.valueOf(params.get("xcxAppid"));
        /**
         * 店铺id
         */
        String storeId = "";
        String storeName = "";

        StoreInfo storeInfo = storeInfoService.getStoreByXcxAppid(authorizerAppId);
        if(storeInfo != null){
            storeId = storeInfo.getId();
            storeName = storeInfo.getStoreName();
        }
        /**
         * 1、使用token调用微信接口modify_domain更换小程序的服务器域名，以便代替微信对小程序或公众号进行运营管理。
         */
        //ApiModifyDomainInfo apiModifyDomainInfo = wechatThirdMiniProgramService.modifyDomain(authorizerAppId, "set", wechatThirdConfig.getRequestDomain(), wechatThirdConfig.getWsrequestDomain(), wechatThirdConfig.getUploadDomain(), wechatThirdConfig.getDownloadDomain());


        /**
         * 2、在微信第三方平台设置页面里上传一个开发小程序的代码的，并添加为模板，取得模板ID
         */
        List<TemplateListResult> templateListResultList = wechatThirdMiniProgramService.getTemplateList();
        /**
         * 取最新的一个模板
         */
        Collections.sort(templateListResultList, Comparator.comparing(TemplateListResult::getCreateTime).reversed());
        TemplateListResult template = templateListResultList.get(0);


        /**
         * 3、在第三方平台开发程序中调用微信接口/wxa/commit传入参数：ext_json
         */
        Map<String, Object> map = new HashMap<>();
        map.put("storeId", storeId);//自定义参数
        ApiCodeCommitExtParameter apiCodeCommitExtParameter = ApiCodeCommitExtParameter
                .builder().extAppid(authorizerAppId)
                .extEnable(true)
                .directCommit(false)
                .ext(map).build();
        //.extPages(pageMap)
        //.pages(Lists.newArrayList("index","search/index"))
        //.networkTimeout(ApiCodeCommitExtParameter.NetworkTimeout.builder().build())
        //.tabBar(ApiCodeCommitExtParameter.TabBar.builder().build())
//                            .window(ApiCodeCommitExtParameter.Window
//                                    .builder()
//                                    .navigationBarTitleText(listAppStore.get(index).getStoreName())
//                                    .build()).build();

        /**
         * 4、在第三方平台开发程序中调用微信接口/wxa/commit传入参数：ext_json
         */
        ApiSetWebviewDomainInfo apiSetWebviewDomainInfo = wechatThirdMiniProgramService.codeCommit(authorizerAppId, template.getTemplateId(), template.getUserVersion(), template.getUserDesc(), apiCodeCommitExtParameter);

        //等待隐私指引检测
        Thread.currentThread().sleep(5000);

        /**
         * 5 获取授权小程序帐号的可选类目
         */
        CategoryListResult categoryList = wechatThirdMiniProgramService.getCategoryList(authorizerAppId);

        /**
         * 6 获取小程序的第三方提交代码的页面配置（仅供第三方开发者代小程序调用）
         */
        PageListResult pageList = wechatThirdMiniProgramService.getPageList(authorizerAppId);


        /**
         * 7 将第三方提交的代码包提交审核
         */
        List<SubmitAuditParameter.Item> items = Lists.newArrayList();
        for (int i = 0; i < categoryList.getCategoryList().size(); i++) {
            if(i<5){
                CategoryListResult.CategoryList category = categoryList.getCategoryList().get(i);
                SubmitAuditParameter.Item item = SubmitAuditParameter.Item.builder()
                        .address(pageList.getPageList().get(0))
                        .tag(getMiniPragramTag(category.getFirstClass(), category.getSecondClass(), category.getThirdClass()))
                        .first_class(category.getFirstClass())
                        .first_id(category.getFirstId())
                        .second_class(category.getSecondClass())
                        .third_class(category.getThirdClass())
                        .third_id(category.getThirdId())
                        .second_id(category.getSecondId())
                        .title(storeName)
                        .build();
                items.add(item);
            }

        }
        SubmitAuditParameter submitAuditParameter = SubmitAuditParameter
                .builder()
                .order_path("user/order/index")
                .item_list(items).build();
        SubmitAuditResult submitAuditResult = wechatThirdMiniProgramService.submitAudit(authorizerAppId, submitAuditParameter);
        return true;
    }

//
//    /**
//     * 授权完成后可提交审核(单独提交)
//     */
//    @PostMapping("/commitOne")
//    public Boolean commitOne(@RequestBody Map<String, Object> params) throws Exception {
//                    /**
//                     * 授权小程序的id
//                     */
//                    String authorizerAppId = params.get("xcxAppid") == null ? null : String.valueOf(params.get("xcxAppid"));
//                    /**
//                     * 店铺id
//                     */
//                    String storeId = "";
//                    String storeName = "";
//
//                    StoreInfo storeInfo = storeInfoService.getStoreByXcxAppid(authorizerAppId);
//                    if(storeInfo != null){
//                        storeId = storeInfo.getId();
//                        storeName = storeInfo.getStoreName();
//                    }
//                    /**
//                     * 1、使用token调用微信接口modify_domain更换小程序的服务器域名，以便代替微信对小程序或公众号进行运营管理。
//                     */
//                    //ApiModifyDomainInfo apiModifyDomainInfo = wechatThirdMiniProgramService.modifyDomain(authorizerAppId, "set", wechatThirdConfig.getRequestDomain(), wechatThirdConfig.getWsrequestDomain(), wechatThirdConfig.getUploadDomain(), wechatThirdConfig.getDownloadDomain());
//
//
//                    /**
//                     * 2、在微信第三方平台设置页面里上传一个开发小程序的代码的，并添加为模板，取得模板ID
//                     */
//                    List<TemplateListResult> templateListResultList = wechatThirdMiniProgramService.getTemplateList();
//                    /**
//                     * 取最新的一个模板
//                     */
//                    Collections.sort(templateListResultList, Comparator.comparing(TemplateListResult::getCreateTime).reversed());
//                    TemplateListResult template = templateListResultList.get(0);
//
//
//                    /**
//                     * 3、在第三方平台开发程序中调用微信接口/wxa/commit传入参数：ext_json
//                     */
//                    Map<String, Object> map = new HashMap<>();
//                    map.put("storeId", storeId);//自定义参数
//                    ApiCodeCommitExtParameter apiCodeCommitExtParameter = ApiCodeCommitExtParameter
//                            .builder().extAppid(authorizerAppId)
//                            .extEnable(true)
//                            .directCommit(false)
//                            .ext(map).build();
//                    //.extPages(pageMap)
//                    //.pages(Lists.newArrayList("index","search/index"))
//                    //.networkTimeout(ApiCodeCommitExtParameter.NetworkTimeout.builder().build())
//                    //.tabBar(ApiCodeCommitExtParameter.TabBar.builder().build())
////                            .window(ApiCodeCommitExtParameter.Window
////                                    .builder()
////                                    .navigationBarTitleText(listAppStore.get(index).getStoreName())
////                                    .build()).build();
//
//                    /**
//                     * 4、在第三方平台开发程序中调用微信接口/wxa/commit传入参数：ext_json
//                     */
//                    ApiSetWebviewDomainInfo apiSetWebviewDomainInfo = wechatThirdMiniProgramService.codeCommit(authorizerAppId, template.getTemplateId(), template.getUserVersion(), template.getUserDesc(), apiCodeCommitExtParameter);
//
//
//                    /**
//                     * 5 获取授权小程序帐号的可选类目
//                     */
//                    CategoryListResult categoryList = wechatThirdMiniProgramService.getCategoryList(authorizerAppId);
//
//                    /**
//                     * 6 获取小程序的第三方提交代码的页面配置（仅供第三方开发者代小程序调用）
//                     */
//                    PageListResult pageList = wechatThirdMiniProgramService.getPageList(authorizerAppId);
//
//
//                    /**
//                     * 7 将第三方提交的代码包提交审核
//                     */
//                    List<SubmitAuditParameter.Item> items = Lists.newArrayList();
//                    for (int i = 0; i < categoryList.getCategoryList().size(); i++) {
//                        if(i<5){
//                            CategoryListResult.CategoryList category = categoryList.getCategoryList().get(i);
//                            SubmitAuditParameter.Item item = SubmitAuditParameter.Item.builder()
//                                    .address(pageList.getPageList().get(0))
//                                    .tag(getMiniPragramTag(category.getFirstClass(), category.getSecondClass(), category.getThirdClass()))
//                                    .first_class(category.getFirstClass())
//                                    .first_id(category.getFirstId())
//                                    .second_class(category.getSecondClass())
//                                    .third_class(category.getThirdClass())
//                                    .third_id(category.getThirdId())
//                                    .second_id(category.getSecondId())
//                                    .title(storeName)
//                                    .build();
//                            items.add(item);
//                        }
//
//                    }
//                    SubmitAuditParameter submitAuditParameter = SubmitAuditParameter
//                            .builder()
//                            .order_path("user/order/index")
//                            .item_list(items).build();
//                    SubmitAuditResult submitAuditResult = wechatThirdMiniProgramService.submitAudit(authorizerAppId, submitAuditParameter);
//        return true;
//    }

    /**
     *手动发布已通过审核的小程序（批量发布）
     */
    @PostMapping("/releaes")
    public Boolean releaesAudited() throws Exception {
        List<AppStore> listAppStore = authorizationInfoService.listAppStore();
        if(listAppStore != null)
        {
            if(listAppStore.size() > 0){
                for(int index=0;index<listAppStore.size();index++){
                    /**
                     * 授权小程序的id
                     */
                    String authorizerAppId = listAppStore.get(index).getAuthorizerAppid();
                    ApiSetWebviewDomainInfo apiSetWebviewDomainInfo=wechatThirdMiniProgramService.releaesAudited(authorizerAppId);
                }
            }
        }

        return true;
    }

    /**
     *手动发布已通过审核的小程序（单独发布）
     */
    @PostMapping("/releaesOne")
    public Boolean releaesAuditedOne(@RequestBody Map<String, Object> params) throws Exception {
                    /**
                     * 授权小程序的id
                     */
                    String authorizerAppId = params.get("xcxAppid") == null ? null : String.valueOf(params.get("xcxAppid"));
                    ApiSetWebviewDomainInfo apiSetWebviewDomainInfo=wechatThirdMiniProgramService.releaesAudited(authorizerAppId);
        return true;
    }

    /**
     *手动发布已通过审核的小程序
     *87013  撤回次数达到上限（每天一次，每个月10次）  慎用
     */
    @PostMapping("/undo/{authorizerAppid}")
    public Boolean undoCodeAudit(@PathVariable("authorizerAppid") String authorizerAppid) throws Exception {
        ApiSetWebviewDomainInfo apiSetWebviewDomainInfo=wechatThirdMiniProgramService.undoCodeAudit(authorizerAppid);
        return apiSetWebviewDomainInfo==null?false:true;
    }

    /**
     *批量配置小程序用户隐私保护指引
     */
    @PostMapping("/setprivacysetting")
    public Boolean setPrivacySetting() throws Exception {
        List<AppStore> listAppStore = authorizationInfoService.listAppStore();
        if(listAppStore != null)
        {
            if(listAppStore.size() > 0){
                for(int index=0;index<listAppStore.size();index++){
                    /**
                     * 授权小程序的id
                     */
                    String authorizerAppId = listAppStore.get(index).getAuthorizerAppid();

                    List<PrivacySetting.SettingList> settingList = Lists.newArrayList();
                        PrivacySetting.SettingList setting1 = PrivacySetting.SettingList.builder()
                                .privacy_key("UserInfo")
                                .privacy_text("授权用户信息（微信昵称、头像），便于方便展示用户个人主页个人资料，提升用户宣传效果")
                                .build();
                    settingList.add(setting1);
//                    PrivacySetting.SettingList setting2 = PrivacySetting.SettingList.builder()
//                            .privacy_key("Location")
//                            .privacy_text("授权用户的当前位置信息，以便用户能精准定位要查找的店铺的位置，可方便快捷的去指定店铺购买商品或服务")
//                            .build();
//                    settingList.add(setting2);
                    PrivacySetting.SettingList setting3 = PrivacySetting.SettingList.builder()
                            .privacy_key("Address")
                            .privacy_text("授权用户的地址信息，在发货时需要用到用户的发货信息，这样用户才能收到货物")
                            .build();
                    settingList.add(setting3);
                    PrivacySetting.SettingList setting4 = PrivacySetting.SettingList.builder()
                            .privacy_key("PhoneNumber")
                            .privacy_text("授权用户的手机号码，在发货时需要用到用户的手机号，以便派货时能及时联系到用户")
                            .build();
                    settingList.add(setting4);
                    PrivacySetting.SettingList setting5 = PrivacySetting.SettingList.builder()
                            .privacy_key("EXOrderInfo")
                            .privacy_text("授权用户的订单信息，便于用户在小程序中追踪订单状态，方便订单管理和客户服务")
                            .build();
                    settingList.add(setting5);
                    PrivacySetting.SettingList setting6 = PrivacySetting.SettingList.builder()
                            .privacy_key("ChooseLocation")
                            .privacy_text("授权用户选择店铺的具体位置，指引用户找到其想去的店铺，减少路线上的时间成本")
                            .build();
                    settingList.add(setting6);
                    PrivacySetting.SettingList setting7 = PrivacySetting.SettingList.builder()
                            .privacy_key("Album")
                            .privacy_text("授权用户的照片或视频读取权限，用来上传商品图片或视频，提升商品的包装形象，便于销售")
                            .build();
                    settingList.add(setting7);
                    PrivacySetting.SettingList setting8 = PrivacySetting.SettingList.builder()
                            .privacy_key("AlbumWriteOnly")
                            .privacy_text("授权相册（仅写入）权限，用户在小程序中看到中意的商品，可将商品图片进行保存，以便下次再次购买时做参考")
                            .build();
                    settingList.add(setting8);
                    PrivacySetting.SettingList setting9 = PrivacySetting.SettingList.builder()
                            .privacy_key("MessageFile")
                            .privacy_text("授权用户的选中的文件权限，可在小程序端上传附件，让客户更清晰的了解商品信息，更好的提供客户服务")
                            .build();
                    settingList.add(setting9);

                    PrivacySetting.OwnerSetting  ownerSetting = PrivacySetting.OwnerSetting.builder()
                            .contact_email("ytchenwei@163.com")
                            .notice_method("通过弹窗")
                            .build();
                    PrivacySetting privacySetting = PrivacySetting.builder()
                            .privacy_ver(2)
                            .owner_setting(ownerSetting)
                            .setting_list(settingList)
                            .build();
                    ApiReturnMsg apiReturnMsg=wechatThirdMiniProgramService.SetPrivacysetting(authorizerAppId,privacySetting);
                }
            }
        }

        return true;
    }

    /**
     *单独配置小程序用户隐私保护指引
     */
    @PostMapping("/setprivacysettingone")
    public Boolean setPrivacySettingOne(@RequestBody Map<String, Object> params) throws Exception {
                    /**
                     * 授权小程序的id
                     */
                    String authorizerAppId = params.get("xcxAppid") == null ? null : String.valueOf(params.get("xcxAppid"));

                    List<PrivacySetting.SettingList> settingList = Lists.newArrayList();
        PrivacySetting.SettingList setting1 = PrivacySetting.SettingList.builder()
                .privacy_key("UserInfo")
                .privacy_text("授权用户信息（微信昵称、头像），便于方便展示用户个人主页个人资料，提升用户宣传效果")
                .build();
        settingList.add(setting1);
//        PrivacySetting.SettingList setting2 = PrivacySetting.SettingList.builder()
//                .privacy_key("Location")
//                .privacy_text("授权用户的当前位置信息，以便用户能精准定位要查找的店铺的位置，可方便快捷的去指定店铺购买商品或服务")
//                .build();
//        settingList.add(setting2);
        PrivacySetting.SettingList setting3 = PrivacySetting.SettingList.builder()
                .privacy_key("Address")
                .privacy_text("授权用户的地址信息，在发货时需要用到用户的发货信息，这样用户才能收到货物")
                .build();
        settingList.add(setting3);
        PrivacySetting.SettingList setting4 = PrivacySetting.SettingList.builder()
                .privacy_key("PhoneNumber")
                .privacy_text("授权用户的手机号码，在发货时需要用到用户的手机号，以便派货时能及时联系到用户")
                .build();
        settingList.add(setting4);
        PrivacySetting.SettingList setting5 = PrivacySetting.SettingList.builder()
                .privacy_key("EXOrderInfo")
                .privacy_text("授权用户的订单信息，便于用户在小程序中追踪订单状态，方便订单管理和客户服务")
                .build();
        settingList.add(setting5);
        PrivacySetting.SettingList setting6 = PrivacySetting.SettingList.builder()
                .privacy_key("ChooseLocation")
                .privacy_text("授权用户选择店铺的具体位置，指引用户找到其想去的店铺，减少路线上的时间成本")
                .build();
        settingList.add(setting6);
        PrivacySetting.SettingList setting7 = PrivacySetting.SettingList.builder()
                .privacy_key("Album")
                .privacy_text("授权用户的照片或视频读取权限，用来上传商品图片或视频，提升商品的包装形象，便于销售")
                .build();
        settingList.add(setting7);
        PrivacySetting.SettingList setting8 = PrivacySetting.SettingList.builder()
                .privacy_key("AlbumWriteOnly")
                .privacy_text("授权相册（仅写入）权限，用户在小程序中看到中意的商品，可将商品图片进行保存，以便下次再次购买时做参考")
                .build();
        settingList.add(setting8);
        PrivacySetting.SettingList setting9 = PrivacySetting.SettingList.builder()
                .privacy_key("MessageFile")
                .privacy_text("授权用户的选中的文件权限，可在小程序端上传附件，让客户更清晰的了解商品信息，更好的提供客户服务")
                .build();
        settingList.add(setting9);

        PrivacySetting.OwnerSetting  ownerSetting = PrivacySetting.OwnerSetting.builder()
                            .contact_email("ytchenwei@163.com")
                            .notice_method("通过弹窗")
                            .build();
                    PrivacySetting privacySetting = PrivacySetting.builder()
                            .privacy_ver(2)
                            .owner_setting(ownerSetting)
                            .setting_list(settingList)
                            .build();
                    ApiReturnMsg apiReturnMsg=wechatThirdMiniProgramService.SetPrivacysetting(authorizerAppId,privacySetting);
        logger.info("setprivacysettingone return: ", apiReturnMsg.toString());
        return true;
    }

    /**
     *获取小程序用户隐私保护指引
     */
    @GetMapping("/getPrivacySetting")
    public String getPrivacySetting(@RequestParam("xcxAppid") String xcxAppid) throws Exception{
        GetPrivacyParam setPrivacyParam = new GetPrivacyParam();
        setPrivacyParam.setPrivacy_ver(1);
        String apiReturnMsg = wechatThirdMiniProgramService.GetPrivacysetting(xcxAppid,setPrivacyParam);
        return apiReturnMsg;
    }
    /**
     *创建开放平台帐号并绑定公众号/小程序
     */
    @PostMapping("/OpenCreate")
    public Boolean OpenCreate(@RequestBody Map<String, Object> params) throws Exception {
        String gzhAppid = params.get("gzhAppid") == null ? null : String.valueOf(params.get("gzhAppid"));
        String xcxAppid = params.get("xcxAppid") == null ? null : String.valueOf(params.get("xcxAppid"));
        String openAppid = "";
        OpenCreateAppid openCreateAppid = OpenCreateAppid.builder()
                .appid(gzhAppid)
                .build();
        ApiOpenCreateReturn apiOpenCreateReturn=wechatThirdMiniProgramService.OpenCreate(gzhAppid,openCreateAppid);
        ApiReturnMsg apiReturnMsg = null;
        if(apiOpenCreateReturn != null){
            openAppid = apiOpenCreateReturn.getOpen_appid();
            OpenBind openBind= OpenBind.builder()
                    .appid(xcxAppid)
                    .open_appid(openAppid)
                    .build();
            apiReturnMsg=wechatThirdMiniProgramService.OpenBind(xcxAppid,openBind);
        }
        return apiReturnMsg==null?false:true;
    }

    /**
     *将公众号/小程序绑定到开放平台帐号下
     */
    @PostMapping("/OpenBind")
    public Boolean OpenBind(@RequestBody Map<String, Object> params) throws Exception {
        String appid = params.get("appId") == null ? null : String.valueOf(params.get("appId"));
        String openAppid = params.get("openAppid") == null ? null : String.valueOf(params.get("openAppid"));
        OpenBind openBind= OpenBind.builder()
                .appid(appid)
                .open_appid(openAppid)
                .build();
        ApiReturnMsg apiReturnMsg=wechatThirdMiniProgramService.OpenBind(appid,openBind);
        return apiReturnMsg==null?false:true;
    }

    /**
     *申请地理位置接口
     */
    @PostMapping("/applyPrivacyInterfaceOne")
    public Boolean ApplyPrivacyInterfaceOne(@RequestBody Map<String, Object> params) throws Exception {
        /**
         * 授权小程序的id
         */
        String authorizerAppId = params.get("xcxAppid") == null ? null : String.valueOf(params.get("xcxAppid"));
        ApplyPrivacyInterfaceParam applyPrivacyInterfaceParam= ApplyPrivacyInterfaceParam.builder()
                .api_name("wx.getLocation")
                .content("用户需要根据自己的地理位置来获取想去的店铺的地址，并依靠地图找到店铺")
                .build();
        ApplyPrivacyReturn applyPrivacyReturn=wechatThirdMiniProgramService.ApplyPrivacyInterfaceOne(authorizerAppId,applyPrivacyInterfaceParam);
        return applyPrivacyReturn==null?false:true;
    }

    /**
     *快速注册企业小程序接口
     */
    @PostMapping("/FastRegisterWeapp")
    public Boolean FastRegisterWeapp(@RequestBody Map<String, Object> params) throws Exception {
        String name = params.get("name") == null ? null : String.valueOf(params.get("name"));
        String code = params.get("code") == null ? null : String.valueOf(params.get("code"));
        Integer code_type = Integer.valueOf(params.get("code_type").toString());
        String legal_persona_wechat = params.get("legal_persona_wechat") == null ? null : String.valueOf(params.get("legal_persona_wechat"));
        String legal_persona_name = params.get("legal_persona_name") == null ? null : String.valueOf(params.get("legal_persona_name"));
        String component_phone = params.get("component_phone") == null ? null : String.valueOf(params.get("component_phone"));
        FastRegisterWeappParam fastRegisterWeappParam = FastRegisterWeappParam.builder()
                .name(name)
                .code(code)
                .code_type(code_type)
                .legal_persona_wechat(legal_persona_wechat)
                .legal_persona_name(legal_persona_name)
                .component_phone(component_phone)
                .build();

        ApiReturnMsg apiReturnMsg = null;
        apiReturnMsg = wechatThirdMiniProgramService.FastRegisterWeapp(fastRegisterWeappParam);
        return apiReturnMsg==null?false:true;
    }

    /**
     *获取小程序违规处罚记录
     */
    @GetMapping("/getIllegalRecords")
    public  ILLegalRecordsResult getIllegalRecords(@RequestParam("xcxAppid") String xcxAppid,
                                     @RequestParam("startTime") Long startTime,
                                     @RequestParam("endTime") Long endTime)throws Exception{
        ILLegalRecordsParam iLLegalRecordsParam = ILLegalRecordsParam
                .builder()
                .start_time(startTime)
                .end_time(endTime).build();
        ILLegalRecordsResult iLLegalRecordsResult = wechatThirdMiniProgramService.getIllegalRecords(xcxAppid, iLLegalRecordsParam);

        return iLLegalRecordsResult;
    }

    /**
     *快速注册企业小程序接口
     */
    @GetMapping("/getVerifyTicket")
    public  String getVerifyTicket()throws Exception{
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("component_appid", "wxde32c694e46edd52");
        jsonObject.put("component_appsecret", "b120c51423253e1be13d7ab21b5c289c");
        jsonObject.put("component_verify_ticket", "ticket@@@O2FsIRDXVFW60nBOvVPjKv6WeSNuCVzGI2YIeLDd4O9cOyRZvT0zWy-jg2tXWoHiZCjEoPGQZK3dFf2OZWXQnQ");
        String str = HttpClientUtil.post("https://api.weixin.qq.com/cgi-bin/component/api_component_token", jsonObject.toJSONString());
        return str;
    }

    private String getMiniPragramTag(String firstClass,String secondClass,String thirdClass){
        String tag=null;
        if(firstClass!=null && this.length(firstClass)<20){
            tag=firstClass;
        }
        if(secondClass!=null && this.length(secondClass)<20){
            tag=tag+" "+secondClass;
        }
        if(this.length(tag)<20 && thirdClass!=null && this.length(thirdClass)<20){
            tag=tag+" "+thirdClass;
        }
        return tag;
    }

    /**
     *获取小程序违规处罚记录
     */
    @GetMapping("/getAccessToken")
    public  String getAccessToken(@RequestParam("appId") String appId)throws Exception{
        return wechatThirdMiniProgramService.getAccessToken2(appId);
    }
    /**
     * 获取字符串的长度，如果有中文，则每个中文字符计为2位     * @param value 指定的字符串     * @return 字符串的长度
     */
    public  int length(String value) {
        int valueLength = 0;
        String chinese = "[\u0391-\uFFE5]";
        /* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
        for (int i = 0; i < value.length(); i++) {
            /* 获取一个字符 */
            String temp = value.substring(i, i + 1);
            /* 判断是否为中文字符 */
            if (temp.matches(chinese)) {
                /* 中文字符长度为2 */
                valueLength += 2;
            } else {
                /* 其他字符长度为1 */
                valueLength += 1;
            }
        }
        return valueLength;
    }

}
